import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> with TickerProviderStateMixin {
  double percentage = 0.0;
  double newPercentage = 0.0;
  late AnimationController percentageAnimationController;
  late ui.Image _localImage;

  @override
  void initState() {
    super.initState();
    setState(() {
      percentage = 0.0;
    });
    _getLocalImage();
    percentageAnimationController = new AnimationController(
        vsync: this, duration: new Duration(milliseconds: 1000))
      ..addListener(() {
        setState(() {
          percentage = ui.lerpDouble(
              percentage, newPercentage, percentageAnimationController.value)!;
        });
      });
  }

  _getLocalImage() async {
    ui.Image imageFrame =
        await getAssetImage('assets/images/caugh.png', width: 200, height: 200);
    setState(() {
      _localImage = imageFrame;
    });
  }

  Future<ui.Image> getAssetImage(String asset, {width, height}) async {
    ByteData data = await rootBundle.load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  Future<ui.Image> getAssetImage2(String asset, BuildContext context,
      {width, height}) async {
    ByteData data = await DefaultAssetBundle.of(context).load(asset);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width, targetHeight: height);
    ui.FrameInfo fi = await codec.getNextFrame();
    return fi.image;
  }

  @override
  Widget build(BuildContext context) {
    final size =MediaQuery.of(context).size;
    final width =size.width;
    final height =size.height;
    print('width is $width; height is $height');

    return new Scaffold(
        appBar: AppBar(
          title: Text('hello22'),
        ),
        body: GestureDetector(
          onTapDown: (TapDownDetails details){
            print('dx:'+'${details.globalPosition.dx}'+'    dy:'+'${details.globalPosition.dy}');
          },
          onLongPressMoveUpdate: (details) => {
            print('dx:'+'${details.globalPosition.dx}'+'    dy:'+'${details.globalPosition.dy}')
            // print('dx:'+'${details.globalPosition.dx}'+'    dy:'+'${details.globalPosition.dy}');
          },
          onHorizontalDragUpdate: (details) => {
            // print('dx:'+'${details.globalPosition.dx}'+'    dy:'+'${details.globalPosition.dy}')
            // print('dx:'+'${details.globalPosition.dx}'+'    dy:'+'${details.globalPosition.dy}');
          },
          onVerticalDragUpdate: (details) => {

          },
          child: new Center(
            child: new Container(
              height: 200,
              width: double.infinity,
              child: new CustomPaint(
                foregroundPainter: new MyPainter(
                  lineColor: Colors.yellow,
                  completeColor: Colors.orange,
                  completePercent: percentage,
                  width: 8.0,
                  // localImage: _localImage
                ),
                child: new Padding(
                  padding: const EdgeInsets.all(0),
                  child: new ElevatedButton(
                      // color: Colors.green,
                      // splashColor: Colors.transparent,
                      // shape: new CircleBorder(),
                      // style: ButtonStyle(shape:),
                      child: new Text("Click"),
                      onPressed: () {
                        // setState(() {
                        //   percentage = newPercentage;
                        //   newPercentage += 10;
                        //   if (newPercentage > 100.0) {
                        //     percentage = 0.0;
                        //     newPercentage = 0.0;
                        //   }
                        //   percentageAnimationController.forward(from: 0.0);
                        // });
                      }),
                ),
              ),
            ),
          ),
        ));
  }
}

class MyPainter extends CustomPainter {
  Color lineColor;
  Color completeColor;
  double completePercent;
  double width;
  // late ui.Image localImage;

  MyPainter({
    required this.lineColor,
    required this.completeColor,
    required this.completePercent,
    required this.width,
    // ui.Image?localImage
  }) {
    int i = 0;
    i++;
  }

  @override
  void paint(Canvas canvas, Size size) {
    Paint line = Paint()
      ..color = lineColor
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke
      ..strokeWidth = width + 20;

    Paint complete = Paint()
      ..color = completeColor
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke
      ..strokeWidth = width;

    Offset center = Offset(size.width / 2, size.height / 2); //  坐标中心
    double radius = min(size.width / 2, size.height / 2); //  半径
    canvas.drawCircle(center, radius, line);

    double arcAngle = 2 * pi * (completePercent / 100);

    canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        -pi / 2, //  从正上方开始
        arcAngle,
        false,
        complete);

    // if (localImage != null) {
    //   canvas.drawImage(localImage, Offset(10, 10), complete);
    // }

    // canvas.drawImage(
    //     Image.asset(
    //       "assets/images/caugh.png",
    //       fit: BoxFit.contain,
    //     ),
    //     Offset(10, 10),
    //     complete);
  }

  // Future<ui.Image> _loadImage(var path, bool isUrl) async {
  //   ImageStream stream;
  //   if (isUrl) {
  //     stream = NetworkImage(path).resolve(ImageConfiguration.empty);
  //   } else {
  //     stream = AssetImage(path, bundle: rootBundle)
  //         .resolve(ImageConfiguration.empty);
  //   }
  //   Completer<ui.Image> completer = Completer<ui.Image>();
  //   void listener(ImageInfo frame, bool synchronousCall) {
  //     final ui.Image image = frame.image;
  //     completer.complete(image);
  //     stream.removeListener(listener);
  //   }

  //   stream.addListener(listener);
  //   return completer.future;
  // }

  // Future<ui.Image> _loadImage(var path,bool isLocal) async{
  //    ImageStream stream;
  //    if (isLocal){
  //      stream = AssetImage(path,bundle: rootBundle).resolve(ImageConfiguration.empty);
  //    } else {
  //      stream = NetworkImage(path).resolve(ImageConfiguration.empty);
  //    }
  //    Completer<ui.Image> completer = Completer<ui.Image>();
  //    void listener(ImageInfo frame,bool synchronousCall){
  //      final ui.Image image = frame.image;
  //      completer.complete(image);
  //      stream.removeListener(listener);
  //    }
  //    stream.addListener(listener);
  //    return completer.future;
  // }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
